<script setup>
//权限管理
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryAllAuth, deleteRoleAuth, addRoleAuth, updateRoleAuth } from '@/api/auth'

onMounted(() => {
  search()
})

const search = async () => {
  try {
    const result = await queryAllAuth(pageNo.value, pageSize.value)
    
    if (result.data.code == 200) {
          console.log('获取用户信息成功')
          console.log(result.data)
          authList.value = result.data.data.records
          total.value = result.data.data.total
    } 
    else {
      ElMessage.error('数据加载失败')
    }

  } catch (error) {
    ElMessage.error('网络请求失败')
  }
}

const authList = ref([])
const pageNo = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total = ref(0)
const dialogVisible = ref(false)
const formRef = ref()
const isEdit = ref(false)

// 表单数据
const formData = ref({
  id: undefined,
  description: '',
  code: '',
  enabled: true
})

const handleSizeChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1
  pageSize.value = val
  pageNo.value = 1 // 重置到第一页
  search()
}

const handleCurrentChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1
  if (val > Math.ceil(total.value / pageSize.value)) {
    val = Math.ceil(total.value / pageSize.value)
  }
  pageNo.value = val
  search()
}

// 添加权限
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    id: undefined,
    description: '',
    code: '',
    enabled: true
  }
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = {
    id: row.id,
    description: row.description,
    code: row.code,
    enabled: row.enabled
  }
  dialogVisible.value = true
}

// 保存权限
const saveAuth = async () => {
  try {
    let result
    if (isEdit.value) {
      // 编辑权限
      result = await updateRoleAuth(formData.value)
    } else {
      // 新增权限
      result = await addRoleAuth(formData.value)
    }
    
    if (result.data.code == 200) {
      ElMessage.success(`${isEdit.value ? '编辑' : '添加'}权限成功`)
      dialogVisible.value = false
      search() // 重新加载数据
    } else {
      ElMessage.error(`${isEdit.value ? '编辑' : '添加'}权限失败: ${result.data.msg}`)
    }
  } catch (error) {
    ElMessage.error(`${isEdit.value ? '编辑' : '添加'}权限失败: ${error.message}`)
  }
}

// 删除权限
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除权限"${row.description}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await deleteRoleAuth(row.id)
      if (result.data.code == 200) {
        ElMessage.success('删除成功')
        search() // 重新加载数据
      } else {
        ElMessage.error(`删除失败: ${result.data.msg}`)
      }
    } catch (error) {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
</script>

<template>
  <div>
    <div id="title">权限管理</div><br>
  </div>
  
  <!-- 功能按钮 -->
  <el-button type="success" @click="handleAdd">+ 新增权限信息</el-button>
  <br><br>
  
  <el-table :data="authList" border style="width: 100%" >
    <el-table-column prop="description" label="描述" align="center" width="250px" />
    <el-table-column prop="code" label="编码" align="center" width="250px" />
    <el-table-column label="状态" width="200px" align="center">
      <template #default="scope">
        <el-button v-if="scope.row.enabled" type="success" plain>启用中</el-button>
        <el-button v-else type="danger" plain>禁用中</el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <br><br>
  
  <div class="container">
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  
  <!-- 添加/编辑权限对话框 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑权限信息' : '新增权限信息'" width="500px">
    <el-form ref="formRef" :model="formData" label-width="80px">
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入权限描述" />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入权限编码" />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-switch
          v-model="formData.enabled"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="saveAuth">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
#title {
  font-size: 20px;
  font-weight: 600;
  color: #e0e0e0;
}
.dialog-footer {
  text-align: right;
}
</style>